package com.echo.boot.proxy;

import com.echo.boot.pojo.Theme;
import com.echo.boot.service.ThemeService;
import com.echo.boot.service.imp.ThemeServiceImp;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA
 * Created By CQ
 * Date: 2020/7/2
 * Time: 17:45
 *
 * @author Administrator
 */
public class CglibProxy implements MethodInterceptor {
    private MyAspect myAspect = new MyAspect();

    private Object target;

    public Object getInstance(Object target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        // 返回代理对象
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println(o.getClass().getName());
        System.out.println(methodProxy.getClass().getName());
        myAspect.befor();
        Object invoke = methodProxy.invoke(target, objects);
        myAspect.after();
        return invoke;
    }

    public static void main(String[] args) {
        ThemeServiceImp imp = new ThemeServiceImp();
        ThemeService instance = (ThemeService) new CglibProxy().getInstance(imp);
        int insert = instance.insert(new Theme());
        System.out.println(insert);
    }
}
